package com.lagou.stage1.module4.task3;

import java.util.concurrent.locks.ReentrantLock;

public class BuyTicketRunnable implements Runnable {
    private static int i = 100;
    private ReentrantLock lock = new ReentrantLock();

    public BuyTicketRunnable(int i) {
        setI(i);
    }

    public static int getI() {
        return i;
    }

    public static void setI(int i) {
        BuyTicketRunnable.i = i;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                //lock.lock();
                //调用之前检测i是否<=0,如果是退出当前循环
                if (i <= 0) {
                    break;
                }

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打印被买走的火车票,并做i--操作
                System.out.println("编号为: " + i-- + "的火车票已经被线程: " + Thread.currentThread().getName() + "购买.");
                //lock.unlock();
            }
        }
    }

    public static void main(String[] args) {

        BuyTicketRunnable btr = new BuyTicketRunnable(i);
        Thread t1 = new Thread(btr);
        Thread t2 = new Thread(btr);
        Thread t3 = new Thread(btr);

        t1.start();
        t2.start();
        t3.start();
        /*//使用join做阻塞
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        System.out.println("主线程开始等待....");
    }
}
